/*=============================================================
(c) 2012 by Juliano Efson Sales
www.mdcc.ufc.br
================================================================*/

namespace HPE.Load {
   
   using System;
   using System.Collections;
   using System.Data;
   using System.IO;
   using System.Xml;
   using System.Xml.Schema;
   using System.Text;
   
   public class XMLValidator {
      protected int ErrorsCount = 0;

      protected string ErrorMessage = "";

      protected string xsd;
     
      public static void ValidationHandler(object sender, ValidationEventArgs args) {
         ErrorMessage = ErrorMessage + args.Message + "\r\n";
         ErrorsCount ++;
      }

      public XMLValidator(string xsd) {
         this.xsd = xsd;
      }

      public bool IsValid(string strXMLDoc) {
         ErrorMessage = "";

         // Declare local objects
         XmlTextReader textReader = null;
         XmlSchemaCollection schemaCollection = null;
         XmlValidatingReader validatingReader = null;
         
         // Text reader object
         textReader = new XmlTextReader(xsd);
         schemaCollection = new XmlSchemaCollection();
         schemaCollection.Add(null, textReader);
         
         validatingReader = new XmlValidatingReader(strXMLDoc, XmlNodeType.Document, null);            
         validatingReader.Schemas.Add(schemaCollection);
         
         validatingReader.ValidationType = ValidationType.Schema;
         validatingReader.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);
         
         while(validatingReader.Read());
         
         validatingReader.Close();

         if (ErrorsCount > 0)
          {
            return false;
         }
         
         return true;
      }
   }
}

